/**
 * HTTP 请求工具类 - 基于 axios 封装
 * 适配三角洲数据查询项目
 */
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type AxiosError, type InternalAxiosRequestConfig } from 'axios'
import { v4 as uuidv4 } from 'uuid'
import { apiConfig, debugConfig, clientConfig } from '@/config/env'
import { getToken } from '@/utils/auth'

// API 响应基础结构
export interface ApiResponse<T = any> {
  code: number
  message: string
  msg?: string // 兼容后端返回的msg字段
  data: T
  timestamp?: number
}

// 移除了请求优先级枚举（队列系统已移除）

// 重试配置接口
export interface RetryConfig {
  maxRetries?: number // 最大重试次数
  retryDelay?: number // 基础重试延迟（毫秒）
  retryMultiplier?: number // 重试延迟倍数（指数退避）
  retryCondition?: (error: any) => boolean // 重试条件判断函数
  maxRetryDelay?: number // 最大重试延迟
}

// 超时配置接口
export interface TimeoutConfig {
  initialTimeout?: number // 初始超时时间
  maxTimeout?: number // 最大超时时间
  timeoutMultiplier?: number // 超时时间倍数
  progressiveTimeout?: boolean // 是否启用渐进式超时
}

// 请求配置接口
export interface RequestOptions {
  headers?: Record<string, string>
  timeout?: number
  params?: Record<string, any>
  withCredentials?: boolean
  skipCache?: boolean // 是否跳过缓存
  skipErrorHandler?: boolean // 是否跳过错误处理
  useFallbackUrl?: boolean // 是否使用备用URL
  retry?: RetryConfig // 重试配置
  timeoutConfig?: TimeoutConfig // 超时配置
}

/**
 * 错误响应处理
 */
class RequestError extends Error {
  status: number
  data: any
  isBusinessError: boolean

  constructor(message: string, status: number, data?: any, isBusinessError: boolean = false) {
    super(message)
    this.name = 'RequestError'
    this.status = status
    this.data = data
    this.isBusinessError = isBusinessError
  }
}

// 移除了优先队列实现，简化为直接请求

/**
 * 重试管理器
 */
class RetryManager {
  private static defaultConfig: Required<RetryConfig> = {
    maxRetries: 3,
    retryDelay: 1000,
    retryMultiplier: 2,
    maxRetryDelay: 10000,
    retryCondition: (error: any) => {
      // 如果是业务逻辑错误，不重试
      if (error instanceof RequestError && error.isBusinessError) {
        return false
      }

      // 默认重试条件：网络错误、超时、5xx服务器错误
      if (!error.response) return true // 网络错误
      const status = error.response.status
      return status >= 500 || status === 408 || status === 429 // 服务器错误、超时、限流
    }
  }

  static async executeWithRetry<T>(
    requestFn: () => Promise<T>,
    config: RetryConfig = {}
  ): Promise<T> {
    const finalConfig = { ...this.defaultConfig, ...config }
    let lastError: any
    let attempt = 0

    while (attempt <= finalConfig.maxRetries) {
      try {
        return await requestFn()
      } catch (error) {
        lastError = error
        attempt++

        // 检查是否应该重试
        if (attempt > finalConfig.maxRetries || !finalConfig.retryCondition(error)) {
          throw error
        }

        // 计算延迟时间（指数退避）
        const delay = Math.min(
          finalConfig.retryDelay * Math.pow(finalConfig.retryMultiplier, attempt - 1),
          finalConfig.maxRetryDelay
        )

        if (SHOW_LOGS && debugConfig.debug) {
          console.log(`🔄 请求重试 ${attempt}/${finalConfig.maxRetries}，${delay}ms后重试`)
        }

        // 等待重试
        await new Promise(resolve => setTimeout(resolve, delay))
      }
    }

    throw lastError
  }
}

/**
 * 超时管理器
 */
class TimeoutManager {
  static getTimeout(attempt: number, config: TimeoutConfig = {}, defaultTimeout: number = 15000): number {
    const finalConfig = {
      initialTimeout: defaultTimeout,
      maxTimeout: defaultTimeout * 3,
      timeoutMultiplier: 1.5,
      progressiveTimeout: true,
      ...config
    }

    if (!finalConfig.progressiveTimeout) {
      return finalConfig.initialTimeout
    }

    // 渐进式超时：每次重试增加超时时间
    const timeout = Math.min(
      finalConfig.initialTimeout * Math.pow(finalConfig.timeoutMultiplier, attempt),
      finalConfig.maxTimeout
    )

    return Math.floor(timeout)
  }
}

// 配置常量 - 从环境变量获取
const BASE_URL = apiConfig.baseUrl
const FALLBACK_URL = apiConfig.fallbackUrl
const DEFAULT_TIMEOUT = apiConfig.timeout
const ENABLE_CACHE = apiConfig.enableCache
const CACHE_PREFIX = apiConfig.cachePrefix
const SHOW_LOGS = debugConfig.showApiLogs
const CLIENT_TYPE = clientConfig.type
const CLIENT_VERSION = clientConfig.version

// 移除了队列相关接口

class Request {
  private instance: AxiosInstance
  private fallbackInstance: AxiosInstance
  private cache = new Map<string, { value: any, expire: number }>()
  private isUsingFallback = false
  private requestDeduplication = new Map<string, Promise<any>>() // 请求去重
  private cacheCleanupTimer: NodeJS.Timeout | null = null // 缓存清理定时器
  private maxCacheSize = 100 // 最大缓存条目数
  private pendingRequests = new Map<string, AbortController>() // 待处理的请求控制器

  constructor() {
    // 创建主 axios 实例
    this.instance = axios.create({
      baseURL: BASE_URL,
      timeout: DEFAULT_TIMEOUT,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })

    // 创建备用 axios 实例
    this.fallbackInstance = axios.create({
      baseURL: FALLBACK_URL,
      timeout: DEFAULT_TIMEOUT,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })

    // 设置请求拦截器
    this.setupRequestInterceptors()

    // 设置响应拦截器
    this.setupResponseInterceptors()

    // 为备用实例也设置相同的拦截器
    this.setupFallbackInterceptors()

    // 启动缓存清理机制
    if (ENABLE_CACHE) {
      this.startCacheCleanup()
    }
  }

  /**
   * 生成客户端唯一ID
   */
  private getClientId(): string {
    const storageKey = 'app_client_id'
    let clientId = localStorage.getItem(storageKey)

    if (!clientId) {
      clientId = uuidv4()
      localStorage.setItem(storageKey, clientId)
    }

    return clientId
  }

  /**
   * 获取设备信息
   */
  private getDeviceInfo(): string {
    const screenWidth = window.screen.width
    const screenHeight = window.screen.height
    const devicePixelRatio = window.devicePixelRatio || 1

    let deviceType = 'Desktop'
    if (/Mobi|Android|iPhone|iPad|iPod/.test(navigator.userAgent)) {
      deviceType = 'Mobile'
    } else if (/Tablet|iPad/.test(navigator.userAgent)) {
      deviceType = 'Tablet'
    }

    return `${deviceType} (${screenWidth}x${screenHeight}, ${devicePixelRatio}x)`
  }

  /**
   * 获取操作系统信息
   */
  private getOSInfo(): { name: string, version: string } {
    const userAgent = navigator.userAgent
    let osName = 'Unknown'
    let osVersion = ''

    if (userAgent.indexOf('Win') !== -1) {
      osName = 'Windows'
      const windowsVersionMatch = userAgent.match(/Windows NT (\d+\.\d+)/)
      osVersion = windowsVersionMatch ? windowsVersionMatch[1] : ''
    } else if (userAgent.indexOf('Mac') !== -1) {
      osName = 'MacOS'
      const macVersionMatch = userAgent.match(/Mac OS X (\d+[._]\d+[._]?\d*)/)
      osVersion = macVersionMatch ? macVersionMatch[1].replace(/_/g, '.') : ''
    } else if (userAgent.indexOf('Linux') !== -1) {
      osName = 'Linux'
    } else if (userAgent.indexOf('Android') !== -1) {
      osName = 'Android'
      const androidVersionMatch = userAgent.match(/Android (\d+(\.\d+)+)/)
      osVersion = androidVersionMatch ? androidVersionMatch[1] : ''
    } else if (/iPhone|iPad|iPod/.test(userAgent)) {
      osName = 'iOS'
      const iosVersionMatch = userAgent.match(/OS (\d+[._]\d+[._]?\d*)/)
      osVersion = iosVersionMatch ? iosVersionMatch[1].replace(/_/g, '.') : ''
    }

    return { name: osName, version: osVersion }
  }

  /**
   * 设置请求拦截器
   */
  private setupRequestInterceptors() {
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // 生成请求ID
        const requestId = uuidv4()
        const osInfo = this.getOSInfo()

        // 添加请求头信息
        config.headers.set('request-id', requestId)
        config.headers.set('client-type', CLIENT_TYPE)
        config.headers.set('client-id', this.getClientId())
        config.headers.set('app-version', CLIENT_VERSION)
        config.headers.set('os', osInfo.name)
        config.headers.set('os-version', osInfo.version)
        config.headers.set('device-model', this.getDeviceInfo())
        config.headers.set('screen-size', `${window.screen.width}x${window.screen.height}`)

        // 自动添加token到请求头
        const token = getToken()
        if (token) {
          config.headers.set('ba-user-token', token)
          config.headers.set('batoken', token)
          config.headers.set('server', 'true')
          config.headers.set('think-lang', 'zh-cn')
        }

        // 优化缓存策略：只有在明确禁用缓存时才添加时间戳
        if (config.method === 'get' && (config as any).skipCache === true) {
          config.params = {
            ...config.params,
            _t: Date.now()
          }
        }

        // 记录请求开始时间
        ;(config as any).requestStartTime = Date.now()
        ;(config as any).requestId = requestId

        // 根据配置决定是否显示日志（减少频繁输出）
        if (SHOW_LOGS && debugConfig.debug) {
          console.log(`🚀 API Request: ${config.method?.toUpperCase()} ${config.url}`)
        }
        return config
      },
      (error) => {
        console.error('❌ Request Error:', error)
        return Promise.reject(error)
      }
    )
  }

  // 移除了队列管理方法，改为直接执行请求

  /**
   * 请求去重
   */
  private getDeduplicationKey(method: string, url: string, data?: any, params?: any): string {
    let key = `${method}:${url}`
    if (data) {
      try {
        key += ':data=' + JSON.stringify(data)
      } catch {
        key += ':data=' + String(data)
      }
    }
    if (params) {
      try {
        key += ':params=' + JSON.stringify(params)
      } catch {
        key += ':params=' + String(params)
      }
    }
    return key
  }

  private async executeWithDeduplication<T>(
    key: string,
    requestFn: () => Promise<T>
  ): Promise<T> {
    // 检查是否有相同的请求正在进行
    const existingRequest = this.requestDeduplication.get(key)
    if (existingRequest) {
      if (SHOW_LOGS && debugConfig.debug) {
        console.log('🔄 请求去重:', key.substring(0, 50) + '...')
      }
      return existingRequest
    }

    // 创建新请求并缓存Promise
    const requestPromise = requestFn().finally(() => {
      // 请求完成后清除去重缓存
      this.requestDeduplication.delete(key)
    })

    this.requestDeduplication.set(key, requestPromise)
    return requestPromise
  }

  /**
   * 缓存相关方法
   */
  private getCacheKey(url: string, params?: any): string {
    let key = url
    if (params) {
      try {
        key += ':' + JSON.stringify(params)
      } catch {
        key += ':' + String(params)
      }
    }
    return key
  }

  private getNextExpireTime(): number {
    const now = new Date()
    const nextHour = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0, 0, 0)
    nextHour.setMinutes(3) // 整点+3分钟
    return nextHour.getTime()
  }

  private setCache(key: string, value: any) {
    if (!ENABLE_CACHE) return

    const expire = this.getNextExpireTime()
    this.cache.set(key, { value, expire })

    try {
      localStorage.setItem(CACHE_PREFIX + key, JSON.stringify({ value, expire }))
    } catch (e) {
      // 只在调试模式下显示缓存警告
      if (SHOW_LOGS && debugConfig.debug) {
        console.warn('缓存写入localStorage失败', e)
      }
    }

    // 每次设置缓存时检查是否需要清理
    if (this.cache.size > this.maxCacheSize * 0.8) {
      // 当缓存达到80%时触发清理
      setTimeout(() => {
        this.cleanExpiredCache()
        this.limitCacheSize()
      }, 0)
    }
  }

  private getCache(key: string): any | null {
    if (!ENABLE_CACHE) return null

    const now = Date.now()

    // 先查内存缓存
    const mem = this.cache.get(key)
    if (mem && mem.expire > now) {
      // 减少缓存命中日志输出
      if (SHOW_LOGS && debugConfig.debug) {
        console.log('🎯 内存缓存命中:', key.substring(0, 50) + '...')
      }
      return mem.value
    }

    // 再查localStorage
    const str = localStorage.getItem(CACHE_PREFIX + key)
    if (str) {
      try {
        const { value, expire } = JSON.parse(str)
        if (expire > now) {
          this.cache.set(key, { value, expire })
          // 减少缓存命中日志输出
          if (SHOW_LOGS && debugConfig.debug) {
            console.log('💾 localStorage缓存命中:', key.substring(0, 50) + '...')
          }
          return value
        }
      } catch (e) {
        // 只在调试模式下显示缓存解析错误
        if (SHOW_LOGS && debugConfig.debug) {
          console.warn('缓存解析失败', e)
        }
      }
    }

    return null
  }



  /**
   * 设置响应拦截器
   */
  private setupResponseInterceptors() {
    this.instance.interceptors.response.use(
      (response: AxiosResponse): any => {
        // 获取请求信息
        const config = response.config
        const requestId = (config as any).requestId
        const requestStartTime = (config as any).requestStartTime
        const requestDuration = Date.now() - requestStartTime

        // 根据配置决定是否显示日志（减少频繁输出）
        if (SHOW_LOGS && debugConfig.debug) {
          console.log(`✅ API Response (${requestDuration}ms): ${config.method?.toUpperCase()} ${config.url}`)
        }

        // 检查API响应状态
        const apiResponse = response.data as ApiResponse

        // 记录API日志到开发工具
        if (debugConfig.debug && typeof window !== 'undefined' && (window as any).__DEV_TOOLS__) {
          (window as any).__DEV_TOOLS__.addApiLog({
            method: config.method?.toUpperCase(),
            url: config.url,
            success: apiResponse.code === 1,
            duration: requestDuration,
            fromCache: false
          })
        }

        // 标准化响应数据：将msg字段转换为message字段
        if (apiResponse && typeof apiResponse === 'object') {
          if (apiResponse.msg && !apiResponse.message) {
            apiResponse.message = apiResponse.msg
          }
        }

        // 检查API响应状态，如果code不为1则抛出错误
        if (apiResponse && apiResponse.code !== 1) {
          const errorMessage = apiResponse.message || apiResponse.msg || '请求失败'
          console.error(`❌ API Error: ${config.method?.toUpperCase()} ${config.url} - ${errorMessage}`)
          // 业务逻辑错误，不应该重试
          return Promise.reject(new RequestError(errorMessage, apiResponse.code || 0, apiResponse, true))
        }

        // 如果是GET请求且响应成功，则缓存结果
        if (config.method === 'get' && apiResponse.code === 1 && (config as any).enableCache) {
          // 生成缓存key时不包含时间戳参数
          const cacheParams = { ...config.params }
          delete cacheParams._t  // 移除时间戳参数
          const cacheKey = this.getCacheKey(config.url || '', cacheParams)
          this.setCache(cacheKey, apiResponse)
          // 减少缓存保存日志输出
          if (SHOW_LOGS && debugConfig.debug) {
            console.log('💾 缓存已保存:', cacheKey.substring(0, 50) + '...')
          }
        }

        // 返回API响应数据而不是整个axios响应对象
        return apiResponse
      },
      async (error: any) => {
        // 获取请求信息
        const config = error.config as any

        // 如果请求被取消，则静默处理，不报错
        if (axios.isCancel(error)) {
          if (SHOW_LOGS && debugConfig.debug) {
            console.log('🚫 请求已取消:', config?.url || '未知URL')
          }
          return Promise.reject(new RequestError('请求已取消', 499))
        }

        // 获取错误信息
        const status = error.response?.status || 500
        const url = config?.url || '未知URL'
        const method = config?.method?.toUpperCase() || 'UNKNOWN'

        // 记录错误日志
        console.error(`❌ API Error (${status}): ${method} ${url}`, error.message || '未知错误')

        // 如果配置了跳过错误处理，则直接抛出错误
        if (config?.skipErrorHandler) {
          return Promise.reject(error)
        }

        // 处理不同类型的错误
        if (error.message && error.message.includes('timeout')) {
          return Promise.reject(new RequestError('请求超时，请稍后重试', 408))
        }

        if (error.message && error.message.includes('Network Error')) {
          return Promise.reject(new RequestError('网络连接失败，请检查您的网络设置', 0))
        }

        // 根据HTTP状态码处理错误
        switch (status) {
          case 400:
            return Promise.reject(new RequestError('请求参数错误', 400, error.response?.data))
          case 401:
            return Promise.reject(new RequestError('未授权，请重新登录', 401))
          case 403:
            return Promise.reject(new RequestError('拒绝访问', 403))
          case 404:
            return Promise.reject(new RequestError('请求的资源不存在', 404))
          case 500:
            return Promise.reject(new RequestError('服务器内部错误', 500))
          default:
            return Promise.reject(new RequestError(`请求失败 (${status})`, status, error.response?.data))
        }
      }
    )
  }

  /**
   * 设置备用实例拦截器
   */
  private setupFallbackInterceptors() {
    // 为备用实例设置相同的响应拦截器
    this.fallbackInstance.interceptors.response.use(
      (response: AxiosResponse): any => {
        // 检查API响应状态
        const apiResponse = response.data as ApiResponse

        // 标准化响应数据：将msg字段转换为message字段
        if (apiResponse && typeof apiResponse === 'object') {
          if (apiResponse.msg && !apiResponse.message) {
            apiResponse.message = apiResponse.msg
          }
        }

        // 检查API响应状态，如果code不为1则抛出错误
        if (apiResponse && apiResponse.code !== 1) {
          const errorMessage = apiResponse.message || apiResponse.msg || '请求失败'
          console.error(`❌ API Error (Fallback): ${response.config.method?.toUpperCase()} ${response.config.url} - ${errorMessage}`)
          // 业务逻辑错误，不应该重试
          return Promise.reject(new RequestError(errorMessage, apiResponse.code || 0, apiResponse, true))
        }

        // 返回API响应数据而不是整个axios响应对象
        return apiResponse
      },
      (error: AxiosError) => {
        // 简单的错误处理
        const status = error.response?.status || 500
        return Promise.reject(new RequestError(`备用服务器请求失败 (${status})`, status, error.response?.data))
      }
    )
  }

  // 获取当前应该使用的实例
  private getInstance(options?: RequestOptions): AxiosInstance {
    if (options?.useFallbackUrl || this.isUsingFallback) {
      return this.fallbackInstance
    }
    return this.instance
  }

  // 切换到备用URL
  private switchToFallback(): void {
    if (!this.isUsingFallback) {
      this.isUsingFallback = true
      console.warn('已切换到备用API服务器:', FALLBACK_URL)
    }
  }

  /**
   * GET 请求（带缓存、优先级、去重、重试和动态超时）
   */
  async get<T = any>(url: string, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const { params, retry, timeoutConfig, ...rest } = options

    // 如果启用了缓存且没有设置跳过缓存，则尝试从缓存获取
    if (ENABLE_CACHE && !options.skipCache) {
      // 生成缓存key时不包含时间戳参数
      const cacheParams = { ...params }
      delete cacheParams._t  // 移除时间戳参数
      const cacheKey = this.getCacheKey(url, cacheParams)
      const cached = this.getCache(cacheKey)
      if (cached) {
        // 减少缓存命中日志输出
        if (SHOW_LOGS && debugConfig.debug) {
          console.log('🎯 GET缓存命中')
        }

        // 记录缓存命中到开发工具
        if (debugConfig.debug && typeof window !== 'undefined' && (window as any).__DEV_TOOLS__) {
          (window as any).__DEV_TOOLS__.addApiLog({
            method: 'GET',
            url: url,
            success: true,
            duration: 0,
            fromCache: true
          })
        }

        return cached
      }
    }

    // 生成去重key
    const deduplicationKey = this.getDeduplicationKey('GET', url, undefined, params)

    // 创建请求函数
    const requestFn = async (): Promise<ApiResponse<T>> => {
      let attempt = 0
      const maxRetries = retry?.maxRetries || 3

      while (attempt <= maxRetries) {
        // 创建取消控制器
        const abortController = new AbortController()
        const requestId = `GET:${url}:${Date.now()}`
        this.pendingRequests.set(requestId, abortController)

        try {
          // 计算当前尝试的超时时间
          const currentTimeout = TimeoutManager.getTimeout(attempt, timeoutConfig, DEFAULT_TIMEOUT)

          // 为缓存请求设置特殊标记，避免添加时间戳
          const config = {
            params,
            ...rest,
            timeout: currentTimeout,
            enableCache: !options.skipCache,  // 标记这是一个需要缓存的请求
            signal: abortController.signal    // 添加取消信号
          }

          if (SHOW_LOGS && debugConfig.debug && attempt > 0) {
            console.log(`🔄 GET请求重试 ${attempt}/${maxRetries}，超时时间: ${currentTimeout}ms`)
          }

          // 尝试使用主实例发送请求
          const result = await this.getInstance(options).get<ApiResponse<T>>(url, config) as unknown as ApiResponse<T>

          // 请求成功，清理控制器
          this.pendingRequests.delete(requestId)
          return result
        } catch (error) {
          // 请求失败，清理控制器
          this.pendingRequests.delete(requestId)
          attempt++

          // 如果使用主实例失败且不是正在使用备用实例，则尝试使用备用实例
          if (!this.isUsingFallback && !options.useFallbackUrl && attempt <= maxRetries) {
            this.switchToFallback()
            console.warn(`主API服务器请求失败，尝试使用备用服务器: ${url}`, error)

            const currentTimeout = TimeoutManager.getTimeout(attempt, timeoutConfig, DEFAULT_TIMEOUT)
            const config = {
              params,
              ...rest,
              timeout: currentTimeout,
              enableCache: !options.skipCache
            }

            try {
              return await this.fallbackInstance.get<ApiResponse<T>>(url, config) as unknown as ApiResponse<T>
            } catch (fallbackError) {
              // 备用服务器也失败，继续重试逻辑
              if (attempt > maxRetries) {
                throw fallbackError
              }
              continue
            }
          }

          // 如果已达到最大重试次数，抛出错误
          if (attempt > maxRetries) {
            throw error
          }

          // 检查是否应该重试
          if (retry?.retryCondition && !retry.retryCondition(error)) {
            throw error
          }

          // 计算重试延迟
          const retryDelay = Math.min(
            (retry?.retryDelay || 1000) * Math.pow(retry?.retryMultiplier || 2, attempt - 1),
            retry?.maxRetryDelay || 10000
          )

          await new Promise(resolve => setTimeout(resolve, retryDelay))
        }
      }

      throw new Error('请求失败：超过最大重试次数')
    }

    // 直接执行请求（移除队列）
    return this.executeWithDeduplication(deduplicationKey, requestFn)
  }

  /**
   * POST 请求（带缓存、优先级和去重）
   */
  async post<T = any>(url: string, data?: any, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const { ...restOptions } = options

    // 如果启用了缓存且没有设置跳过缓存，则尝试从缓存获取
    if (ENABLE_CACHE && !options.skipCache) {
      // 构造缓存key
      let cacheKey = url
      if (data) {
        try {
          cacheKey += ':data=' + JSON.stringify(data)
        } catch {
          cacheKey += ':data=' + String(data)
        }
      }
      if (options.params) {
        try {
          cacheKey += ':params=' + JSON.stringify(options.params)
        } catch {
          cacheKey += ':params=' + String(options.params)
        }
      }

      // 检查缓存
      const cached = this.getCache(cacheKey)
      if (cached) {
        // 减少缓存命中日志输出
        if (SHOW_LOGS && debugConfig.debug) {
          console.log('🎯 POST缓存命中')
        }

        // 记录缓存命中到开发工具
        if (debugConfig.debug && typeof window !== 'undefined' && (window as any).__DEV_TOOLS__) {
          (window as any).__DEV_TOOLS__.addApiLog({
            method: 'POST',
            url: url,
            success: true,
            duration: 0,
            fromCache: true
          })
        }

        return Promise.resolve(cached)
      }
    }

    // 生成去重key
    const deduplicationKey = this.getDeduplicationKey('POST', url, data, options.params)

    // 创建请求函数
    const requestFn = async (): Promise<ApiResponse<T>> => {
      // 创建取消控制器
      const abortController = new AbortController()
      const requestId = `POST:${url}:${Date.now()}`
      this.pendingRequests.set(requestId, abortController)

      try {
        const { headers, timeout, params, withCredentials } = restOptions
        const config: AxiosRequestConfig = {
          headers,
          timeout,
          params,
          withCredentials,
          signal: abortController.signal  // 添加取消信号
        }

        const result = await this.instance.post<ApiResponse<T>>(url, data, config) as unknown as ApiResponse<T>

        // 请求成功，清理控制器
        this.pendingRequests.delete(requestId)

      // 缓存成功响应
      if (ENABLE_CACHE && !options.skipCache && result && typeof result === 'object' && (!('code' in result) || result.code === 1 || result.code === 200)) {
        // 重新构造缓存key（与上面逻辑保持一致）
        let cacheKey = url
        if (data) {
          try {
            cacheKey += ':data=' + JSON.stringify(data)
          } catch {
            cacheKey += ':data=' + String(data)
          }
        }
        if (options.params) {
          try {
            cacheKey += ':params=' + JSON.stringify(options.params)
          } catch {
            cacheKey += ':params=' + String(options.params)
          }
        }

        this.setCache(cacheKey, result)
        // 减少缓存保存日志输出
        if (SHOW_LOGS && debugConfig.debug) {
          console.log('💾 POST缓存已保存')
        }
      }

        return result
      } catch (error) {
        // 请求失败，清理控制器
        this.pendingRequests.delete(requestId)
        throw error
      }
    }

    // 直接执行请求（移除队列）
    return this.executeWithDeduplication(deduplicationKey, requestFn)
  }

  /**
   * PUT 请求
   */
  async put<T = any>(url: string, data?: any, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const { headers, timeout, params, withCredentials } = options
    const config: AxiosRequestConfig = {
      headers,
      timeout,
      params,
      withCredentials,
    }

    return await this.instance.put<ApiResponse<T>>(url, data, config) as unknown as ApiResponse<T>
  }

  /**
   * DELETE 请求
   */
  async delete<T = any>(url: string, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const { headers, timeout, params, withCredentials } = options
    const config: AxiosRequestConfig = {
      headers,
      timeout,
      params,
      withCredentials,
    }

    return await this.instance.delete<ApiResponse<T>>(url, config) as unknown as ApiResponse<T>
  }

  /**
   * 上传文件
   */
  async upload<T = any>(url: string, file: File, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const formData = new FormData()
    formData.append('file', file)

    const { headers, timeout, params, withCredentials } = options
    const config: AxiosRequestConfig = {
      headers: {
        'Content-Type': 'multipart/form-data',
        ...headers
      },
      timeout,
      params,
      withCredentials,
    }

    return await this.instance.post<ApiResponse<T>>(url, formData, config) as unknown as ApiResponse<T>
  }

  /**
   * 清理过期缓存
   */
  private cleanExpiredCache() {
    const now = Date.now()
    let cleanedCount = 0

    // 清理内存缓存中的过期项
    for (const [key, item] of this.cache.entries()) {
      if (item.expire <= now) {
        this.cache.delete(key)
        cleanedCount++
      }
    }

    // 清理localStorage中的过期项
    const keysToRemove: string[] = []
    Object.keys(localStorage).forEach(key => {
      if (key.startsWith(CACHE_PREFIX)) {
        try {
          const data = JSON.parse(localStorage.getItem(key) || '{}')
          if (data.expire && data.expire <= now) {
            keysToRemove.push(key)
          }
        } catch {
          // 解析失败的也删除
          keysToRemove.push(key)
        }
      }
    })

    keysToRemove.forEach(key => {
      localStorage.removeItem(key)
      cleanedCount++
    })

    // 只在调试模式下显示清理日志
    if (SHOW_LOGS && debugConfig.debug && cleanedCount > 0) {
      console.log(`🧹 已清理 ${cleanedCount} 个过期缓存项`)
    }

    return cleanedCount
  }

  /**
   * 限制缓存大小，删除最旧的缓存项
   */
  private limitCacheSize() {
    if (this.cache.size <= this.maxCacheSize) return

    // 按过期时间排序，删除最旧的项
    const entries = Array.from(this.cache.entries())
    entries.sort((a, b) => a[1].expire - b[1].expire)

    const itemsToRemove = entries.slice(0, this.cache.size - this.maxCacheSize)
    itemsToRemove.forEach(([key]) => {
      this.cache.delete(key)
      // 同时删除localStorage中的对应项
      try {
        localStorage.removeItem(CACHE_PREFIX + key)
      } catch {
        // 忽略删除错误
      }
    })

    if (SHOW_LOGS && debugConfig.debug && itemsToRemove.length > 0) {
      console.log(`🧹 已删除 ${itemsToRemove.length} 个最旧的缓存项以限制缓存大小`)
    }
  }

  /**
   * 启动定时清理
   */
  private startCacheCleanup() {
    // 清理现有定时器
    if (this.cacheCleanupTimer) {
      clearInterval(this.cacheCleanupTimer)
    }

    // 每5分钟清理一次过期缓存
    this.cacheCleanupTimer = setInterval(() => {
      this.cleanExpiredCache()
      this.limitCacheSize()
    }, 5 * 60 * 1000) // 5分钟

    // 立即执行一次清理
    this.cleanExpiredCache()
    this.limitCacheSize()
  }

  /**
   * 停止定时清理
   */
  private stopCacheCleanup() {
    if (this.cacheCleanupTimer) {
      clearInterval(this.cacheCleanupTimer)
      this.cacheCleanupTimer = null
    }
  }

  /**
   * 清除所有缓存
   */
  clearCache() {
    this.cache.clear()
    // 清除localStorage中的缓存
    Object.keys(localStorage).forEach(key => {
      if (key.startsWith(CACHE_PREFIX)) {
        localStorage.removeItem(key)
      }
    })

    // 只在调试模式下显示缓存清除日志
    if (SHOW_LOGS && debugConfig.debug) {
      console.log('🗑️ 缓存已清除')
    }
  }

  /**
   * 获取缓存状态信息（用于调试）
   */
  getCacheInfo() {
    const memoryCache = Array.from(this.cache.entries()).map(([key, value]) => ({
      key,
      expire: new Date(value.expire).toLocaleString(),
      expired: value.expire < Date.now()
    }))

    const localStorageCache = Object.keys(localStorage)
      .filter(key => key.startsWith(CACHE_PREFIX))
      .map(key => {
        try {
          const data = JSON.parse(localStorage.getItem(key) || '{}')
          return {
            key: key.replace(CACHE_PREFIX, ''),
            expire: new Date(data.expire).toLocaleString(),
            expired: data.expire < Date.now()
          }
        } catch {
          return {
            key: key.replace(CACHE_PREFIX, ''),
            expire: '解析失败',
            expired: true
          }
        }
      })

    const info = {
      enabled: ENABLE_CACHE,
      prefix: CACHE_PREFIX,
      memoryCache: {
        count: memoryCache.length,
        items: memoryCache
      },
      localStorage: {
        count: localStorageCache.length,
        items: localStorageCache
      }
    }

    return info
  }

  /**
   * 取消所有待处理的请求
   */
  cancelAllRequests() {
    let cancelledCount = 0

    // 取消所有待处理的请求
    for (const [, controller] of this.pendingRequests.entries()) {
      try {
        controller.abort()
        cancelledCount++
      } catch (error) {
        // 忽略取消错误
      }
    }

    // 清空待处理请求映射
    this.pendingRequests.clear()

    // 清空请求去重缓存
    this.requestDeduplication.clear()

    if (SHOW_LOGS && debugConfig.debug && cancelledCount > 0) {
      console.log(`🚫 已取消 ${cancelledCount} 个待处理的请求`)
    }

    return cancelledCount
  }

  /**
   * 取消特定URL的请求
   */
  cancelRequest(url: string) {
    let cancelledCount = 0

    for (const [requestId, controller] of this.pendingRequests.entries()) {
      if (requestId.includes(url)) {
        try {
          controller.abort()
          this.pendingRequests.delete(requestId)
          cancelledCount++
        } catch (error) {
          // 忽略取消错误
        }
      }
    }

    if (SHOW_LOGS && debugConfig.debug && cancelledCount > 0) {
      console.log(`🚫 已取消 ${cancelledCount} 个 ${url} 相关的请求`)
    }

    return cancelledCount
  }
}

// 创建请求实例
const request = new Request()

// 在开发环境下，将调试方法挂载到全局对象上
if (debugConfig.debug && typeof window !== 'undefined') {
  ;(window as any).__API_DEBUG__ = {
    // 缓存相关
    getCacheInfo: () => request.getCacheInfo(),
    clearCache: () => request.clearCache(),
    cleanExpiredCache: () => request['cleanExpiredCache'](),
    limitCacheSize: () => request['limitCacheSize'](),
    getCache: (key: string) => request['getCache'](key),
    setCache: (key: string, value: any) => request['setCache'](key, value),

    // 请求控制
    cancelAllRequests: () => request.cancelAllRequests(),
    cancelRequest: (url: string) => request.cancelRequest(url),
    getPendingRequestsCount: () => request['pendingRequests'].size,

    // 实用工具
    testTimeout: (url: string, timeout: number) => {
      return request.get(url, { timeout, skipCache: true })
    },
    testRetry: (url: string, maxRetries: number) => {
      return request.get(url, {
        retry: { maxRetries },
        skipCache: true
      })
    }
  }

  // 只在首次加载时显示一次提示
  if (!(window as any).__API_DEBUG_LOADED__) {
    console.log('🔧 API调试工具已挂载到 window.__API_DEBUG__')
    console.log('📊 可用方法: getCacheInfo, testTimeout, testRetry 等')
    ;(window as any).__API_DEBUG_LOADED__ = true
  }
}

// 导出请求实例
export default request

// 导出类型
export type { AxiosRequestConfig, AxiosResponse }
